#!/usr/bin/env python
#coding=utf-8


from subprocess import Popen, PIPE
import platform

'''
通用组件函数库
@author:sftang
@qq:249545020
@mail:xingsu1021@sina.com
'''


def python_ver():
    '''
    返回python的版本号

    '''
    
    return platform.python_version()

def arch():
    '''
    返回平台处理器架构

    '''

    return platform.machine()

def mypopen(cmd):
    '''
    shell命令调用块
    '''
    return Popen(cmd, shell=True, close_fds=True, stdout=PIPE, stderr=PIPE)


def get_output(cmd,removelf=''):
    '''
    执行shell命令块,返回执行正确与错误信息,加上参数removelf可使输出去掉换行
    '''
    ret = Popen(cmd, shell=True, close_fds=True, stdout=PIPE, stderr=PIPE)
    stdoutdata,stderrdata = ret.communicate()
    if removelf != '':
        stdoutdata = stdoutdata.split('\n')[0]
    return stdoutdata,stderrdata


class RsyncDirectoryTree(object):
    '''
    rsync同步操作函数
    '''
    __DEFAULT_ARGS = "-a --delete"
    __RSYNC_PATH = "/usr/bin"

    def __init__(self, rsyncPath =__RSYNC_PATH):
        """
        RsyncDirectoryTree constructor.

        @keyword rsyncPath: The path to rsync (default = /usr/bin).
        """
        self.__rsyncPath = rsyncPath

    def rsync(self, src, dst, args=__DEFAULT_ARGS):
        """
        Wrapper for the rsync command. Synchronize the source directory to the
        destination directory.

        @param src: The source directory.
        @param dst: The destination directory.
        @keyword args: The rsync command line arguments.
        """
        src = src.strip()

        cmd = "%s/rsync %s %s %s" % (self.__rsyncPath, args, src, dst)

        print "cmd===>",cmd
        #/usr/bin/rsync -vzrtopg --progress --delete  tetrasys-design.net::test /dat0/rsync/tetrasys-design.net
        try:
            process = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE,
                            env={"PATH": "%s" % self.__RSYNC_PATH})
            stdoutdata, stderrdata = process.communicate()
        except (OSError, ValueError), e:
            msg = "Could not synchronize directory tree %s to %s." % (src, dst)
            return {'code':1,'errmsg':msg}

        if stderrdata:
            msg = "RsyncDirectoryTree: %s" % stderrdata
            return {'code':1,'errmsg':msg}

        return {'code':0,'msg':'rsync ok'}
    
    
def load_func(pyscript):

    '''
    载入脚本函数
    '''
    pymodule = pyscript
    func = pymodule.split('.')[-1]
    exec "from %s import %s" % (pymodule,func)
    return eval(func)
    

def sumfile(fobj):
    '''
    读取文件，返回文件的hash值
    '''
    try:
        import hashlib
        m = hashlib.md5()
    except ImportError:
        import md5
        m = md5.new()
        
    while True:
        d = fobj.read(8096)
        if not d:
            break
        m.update(d)
    return m.hexdigest()


def md5sum(fname):
    '''
    返回文件的md5值
    '''

    try:
        f = file(fname, 'rb')
    except:
        return False
    ret = sumfile(f)
    f.close()
    
    return ret